#include "tcpserver.hpp"

using namespace TcpServerModule;

// int main()
// {
//     auto tsvr = std::make_unique<TcpServer>(nullptr);
//     tsvr->InitServer();
//     tsvr->Start();
//     return 0;
// }

// #include <sys/types.h>
// #include <sys/socket.h>
// #include <netinet/in.h>
// #include <arpa/inet.h>
// #include "log.hpp"
// #include <cstring>
// #include <string>

// using namespace LogModule;
// #define BACKLOG 8

int main()
{
    int listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (listensockfd < 0)
    {
        LOG(ERROR) << "创建套接字失败";
        return 1;
    }
    LOG(INFO) << "创建套接字成功,listensockfd is:" << listensockfd;

    // 填充网络信息
    struct sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = ::htons(8080);
    local.sin_addr.s_addr = INADDR_ANY;
    // 设置信息
    int n = ::bind(listensockfd, (sockaddr *)&local, sizeof(local));
    if (n < 0)
    {
        LOG(ERROR) << "bind失败";
        return 2;
    }
    LOG(INFO) << "bind成功";
    n = ::listen(listensockfd, BACKLOG);
    if (n < 0)
    {
        LOG(ERROR) << "listen fail";
        return 3;
    }
    struct sockaddr_in peer;
    socklen_t len = sizeof(peer);
    int sockfd = ::accept(listensockfd, (sockaddr *)&peer, &len);
    if (sockfd < 0)
    {
        LOG(ERROR) << "accept error";
        return 4;
    }
    LOG(INFO) << "accept success, sockfd is:" << sockfd;
    char buffer[1024];
    while (true)
    {

        ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::string echo_string = "sever# ";
            echo_string += buffer;
            LOG(INFO) << "收到客户端消息:" << echo_string;
            send(sockfd, echo_string.c_str(), echo_string.size(), 0);
        }
    }

    return 0;
}
